/*
 * Copyright (C) 2010 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;

import org.apache.http.HttpHost;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.download.DownloadManager;
import com.mol.market.common.download.DownloadManager.EnqueueListener;
import com.mol.market.common.download.DownloadService;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.HttpClientFactory;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.network.ResponseCacheManager;
import com.mol.market.common.util.AlarmManageUtils;
import com.mol.market.common.util.CacheManager;
import com.mol.market.common.util.DialogUtil;
import com.mol.market.common.util.DialogUtil.YesNoDialogListener;
import com.mol.market.common.util.ThemeManager;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.UpdateInfo;
import com.mol.market.common.widget.BaseTabActivity;
import com.mol.market.ui_v4.AppManagerActivity;
import com.mol.market.ui_v4.MasterTabActivity;

/**
 * Home Tab Activity : 机锋市场的入口页面
 * 
 * @author Andrew
 * @date 2011-5-9
 * @since Version 0.7.0
 */
public class HomeTabActivity extends BaseTabActivity implements ApiAsyncTask.ApiRequestListener,
        OnTabChangeListener, Observer, OnClickListener {

    // hide notification bar
    private static final int HIDE_NOTIFICATION = 1;
    // make notification duration 5 secs
    private static final int NOTIFICATION_DURATION = 5000;
    
    // hide tipView
    private static final int HIDE_TIPVIEW = 2;

    // exit menu dialog
    private static final int DIALOG_EXIT = 1;
    private static final int DIALOG_OPT_UPDATE = 2;
    private static final int DIALOG_FORCE_UPDATE = 3;

    // Tab id
    private static final String TAB_HOME = "home";
    private static final String TAB_CATEGORY = "category";
    private static final String TAB_RECOMMEND = "recommend";
    private static final String TAB_RANK = "rank";
    private static final String TAB_APP = " app";

    private TabHost mTabHost;
    private ImageView mMover;
    private int mStartX;
    private int mUpdateCounter;
    // 浮动提醒框
    private RelativeLayout mNotificationView;
    private TextView mNotificationContent;
    // 类似于Toast的提示框
    private RelativeLayout mTipView;
    private TextView mTipContent;

    // 检查用户是否切换CMWAP网络
    private BroadcastReceiver mNetworkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            HttpHost proxy = Utils.detectProxy(getApplicationContext());
            if (proxy != null) {
                HttpClientFactory.get().getHttpClient().useProxyConnection(proxy);
            } else {
                HttpClientFactory.get().getHttpClient().useDefaultConnection();
            }
        }
    };
    
    // 检查用户是否更换主题
    private BroadcastReceiver mThemeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            initSkin();
        }
    };

    // 检查机锋市场版本更新
    private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constants.BROADCAST_FORCE_EXIT)) {
                // 强制退出机锋市场
                exit();
            } else if (action.equals(Constants.BROADCAST_REMIND_LATTER)) {
                // do nothing
            } else if (action.equals(Constants.BROADCAST_DOWNLOAD_OPT)) {
                // start download
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mSession
                        .getUpdateUri()));
                request.setPackageName(mSession.getPackageName());
                request.setTitle(Constants.UPDATE_FILE_NAME);
                request.setShowRunningNotification(true);
                request.setSourceType(com.mol.market.common.download.Constants.DOWNLOAD_FROM_OTA);
                request.setMimeType(com.mol.market.common.download.Constants.MIMETYPE_APK);
                mSession.getDownloadManager().enqueue(context, request, new EnqueueListener() {

                    @Override
                    public void onFinish(long id) {
                        mSession.setUpdateID(id);
                    }
                });
                mSession.mIsDownloadOta = true;
                
            } else if (action.equals(Constants.BROADCAST_DOWNLOAD)) {
                // start download
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mSession
                        .getUpdateUri()));
                request.setPackageName(mSession.getPackageName());
                request.setTitle(Constants.UPDATE_FILE_NAME);
                request.setShowRunningNotification(true);
                request.setSourceType(com.mol.market.common.download.Constants.DOWNLOAD_FROM_OTA);
                request.setMimeType(com.mol.market.common.download.Constants.MIMETYPE_APK);
                mSession.getDownloadManager().enqueue(context, request, new EnqueueListener() {

                    @Override
                    public void onFinish(long id) {
                        mSession.setUpdateID(id);
                    }
                });
                mSession.mIsDownloadOta = true;
                HomeTabActivity.this.finish();
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setTheme(mSession.getTheme());
        
        // 接受更新提醒
        mSession.addObserver(this);
        
        // 获取返利平台
        registerReceivers();

        setContentView(R.layout.activity_home_tab_main);

        @SuppressWarnings("unchecked")
        HashMap<String, Object> item = (HashMap<String, Object>) getIntent().getSerializableExtra(
                Constants.EXTRA_HOME_DATA);
        initView(item);

        // send product update broadcast
        if (Utils.isNeedCheckUpgrade(getApplicationContext())) {
            mSession.setUpdataCheckTime(System.currentTimeMillis());
            MarketAPI.submitAllInstalledApps(getApplicationContext());
        }
        
        // 点击下载列表回到应用或者更新提醒
        Intent i = getIntent();
        if (i != null) {
            boolean isClick = i.getBooleanExtra(Constants.CLICK_DOWNLOADING, false);
            if (isClick) {
                mTabHost.setCurrentTabByTag(TAB_APP);
            } else {
                // 点击更新回到应用不再检查更新
                MarketAPI.checkUpgrade(getApplicationContext(), this);
            }
        }

        // 网络正常，开始检查版本更新
        MarketAPI.checkUpdate(getApplicationContext(), this);
        MarketAPI.getFollowedRecommend(getApplicationContext(), this);
        checkNewSplash();

        if (mSession.isFirstLogin()) {
            mSession.setFirstLogin(false);
            gotoTabVersion();
            MarketAPI.getRequired(getApplicationContext(), this);
            AlarmManageUtils.notifyPushService(getApplicationContext(), false);
            createDesktopIcon();
        }
        
        if(!mSession.getIsShowTipAtSecond() && mSession.isSecondLogin()){
            
            showTip(getString(R.string.widget_showtip),false);
            
            //改变标志位
            mSession.setIsShowTipAtSecond(true);
        }
    }

    /*
     * 推荐安装平板版
     */
    private void gotoTabVersion() {
        if (mSession.screenHeight >= 960 || mSession.screenWidth >= 960) {
            DialogUtil.createYesNoDialog(this, 1, 
                    "检测到您的设备分辨率较高，建议安装机锋市场pad版获得更好体验", new YesNoDialogListener() {
                
                @Override
                public void onYesDialog(int id) {
                    Intent detailIntent = new Intent(getApplicationContext(), com.mol.market.ui_v4.ProductDetailActivity.class);
                    detailIntent.putExtra(Constants.EXTRA_PACKAGE_NAME, "com.mappn.pad.gfan");
                    startActivity(detailIntent);
                }
                
                @Override
                public void onNoDialog(int id) {
                    // no process
                }
            }).show();
        }
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        
        if (intent != null) {
            boolean isClick = intent.getBooleanExtra(Constants.CLICK_DOWNLOADING, false);
            if (isClick) {
                mTabHost.setCurrentTabByTag(TAB_APP);
            }
        }
    }
    
    /**
     * 检查是否需要弹出应用更新通知
     */
    private void checkUpdateAppsNotification() {

        if (mSession.isNotificationUpdateApps() && mSession.getUpgradeNumber() > 0) {
            NotificationManager notificationManager = 
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            Notification notification = new Notification();
            notification.defaults = Notification.DEFAULT_LIGHTS;
            notification.icon = R.drawable.notification_icon;
            notification.tickerText = getString(R.string.notification_update_info,
                    mSession.getUpgradeNumber());
            notification.when = System.currentTimeMillis();
            Intent intent = new Intent(Constants.BROADCAST_CLICK_INTENT);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                    intent, PendingIntent.FLAG_CANCEL_CURRENT);
            notification.setLatestEventInfo(getApplicationContext(),
                    getString(R.string.notification_update_info_title),
                    getString(R.string.notification_update_info, mSession.getUpgradeNumber()),
                    pendingIntent);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(R.drawable.notification_icon, notification);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
        mIsPortraitInit = false;
        mIsLandscapeInit = false;
        LocalActivityManager lam = getLocalActivityManager();
        lam.removeAllActivities();
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (Configuration.ORIENTATION_LANDSCAPE == newConfig.orientation
                || Configuration.KEYBOARDHIDDEN_NO == newConfig.hardKeyboardHidden) {
            // 用户选择横屏或者切换全键盘
            mIsLandscape = true;
        } else {
            // 用户选择竖屏
            mIsLandscape = false;
        }
        mIsRotated = true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentTab", mTabHost.getCurrentTab());
    }

    @Override
    protected void onRestoreInstanceState(Bundle state) {
        super.onRestoreInstanceState(state);
        mLastTab = state.getInt("currentTab");
        mIsRestore = true;
        mTabHost.setCurrentTab(mLastTab);
    }
    
    private void registerReceivers() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkReceiver, filter);

        IntentFilter updatefilter = new IntentFilter();
        updatefilter.addAction(Constants.BROADCAST_FORCE_EXIT);
        updatefilter.addAction(Constants.BROADCAST_REMIND_LATTER);
        updatefilter.addAction(Constants.BROADCAST_DOWNLOAD_OPT);
        updatefilter.addAction(Constants.BROADCAST_DOWNLOAD);
        registerReceiver(mUpdateReceiver, updatefilter);

        IntentFilter themeFilter = new IntentFilter(Constants.BROADCAST_CHANGE_THEME);
        registerReceiver(mThemeReceiver, themeFilter);
    }

    private void unregisterReceiver() {
        unregisterReceiver(mNetworkReceiver);
        unregisterReceiver(mUpdateReceiver);
        unregisterReceiver(mThemeReceiver);
    }
    
    /*
     * 换肤
     */
    private void initSkin() {

        View tabBg = findViewById(R.id.tab_frame_layout);
        tabBg.setBackgroundResource(ThemeManager.getResource(mSession, 
                ThemeManager.KEY_HOME_TAB_BACKGROUND));
        
        mMover.setImageResource(ThemeManager.getResource(mSession,
                ThemeManager.KEY_HOME_TAB_INDICATOR));
        for (int i = 0; i < 5; i++) {

            View v = mTabHost.getTabWidget().getChildTabViewAt(i);

            switch (i) {
            case 0:
                createTabView(getApplicationContext(), getString(R.string.main_tab_index),
                        ThemeManager.KEY_HOME_TAB_INDEX, v);
                break;
            case 1:
                createTabView(getApplicationContext(), getString(R.string.main_tab_sort),
                        ThemeManager.KEY_HOME_TAB_CATEGORY, v);
                break;
            case 2:
                createTabView(getApplicationContext(), getString(R.string.main_tab_promotion),
                        ThemeManager.KEY_HOME_TAB_RECOMMEND, v);
                break;
            case 3:
                createTabView(getApplicationContext(), getString(R.string.main_tab_rank),
                        ThemeManager.KEY_HOME_TAB_RANK, v);
                break;
            case 4:
                createTabView(getApplicationContext(), getString(R.string.main_tab_app), -1, v);
                break;

            default:
                break;
            }
        }
    }

    /*
     * 初始化Tab Host 包含四个Tab（首页、分类、排行、应用管理）
     */
    private void initView(HashMap<String, Object> item) {

        mTabHost = (TabHost) this.findViewById(android.R.id.tabhost);
        mTabHost.setup();

        View tabBg = findViewById(R.id.tab_frame_layout);
        tabBg.setBackgroundResource(ThemeManager.getResource(mSession, 
                ThemeManager.KEY_HOME_TAB_BACKGROUND));
        
        Intent i = new Intent(getApplicationContext(), HomeActivityTab.class);
        i.putExtra(Constants.EXTRA_HOME_DATA, item);
        TabSpec tab1 = mTabHost
                .newTabSpec(TAB_HOME)
                .setIndicator(
                        createTabView(getApplicationContext(), getString(R.string.main_tab_index),
                                ThemeManager.KEY_HOME_TAB_INDEX, null)).setContent(i);
        mTabHost.addTab(tab1);

        Intent categoryIntent = new Intent(getApplicationContext(), CategoryGridActivity.class);
        categoryIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        TabSpec tab2 = mTabHost
                .newTabSpec(TAB_CATEGORY)
                .setIndicator(
                        createTabView(getApplicationContext(), getString(R.string.main_tab_sort),
                                ThemeManager.KEY_HOME_TAB_CATEGORY, null))
                .setContent(categoryIntent);
        mTabHost.addTab(tab2);

        TabSpec tab3 = mTabHost
                .newTabSpec(TAB_RECOMMEND)
                .setIndicator(
                        createTabView(getApplicationContext(), 
                                getString(R.string.main_tab_promotion),
                                ThemeManager.KEY_HOME_TAB_RECOMMEND, null))
                .setContent(new Intent(getApplicationContext(), MasterTabActivity.class));
        mTabHost.addTab(tab3);

        Intent rankIntent = new Intent(getApplicationContext(), RankTabActivity.class);
        rankIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        TabSpec tab4 = mTabHost
                .newTabSpec(TAB_RANK)
                .setIndicator(
                        createTabView(getApplicationContext(), getString(R.string.main_tab_rank),
                                ThemeManager.KEY_HOME_TAB_RANK, null))
                .setContent(rankIntent);
        mTabHost.addTab(tab4);

        TabSpec tab5 = mTabHost
                .newTabSpec(TAB_APP)
                .setIndicator(
                        createTabView(getApplicationContext(), 
                                getString(R.string.main_tab_app), -1, null))
                .setContent(new Intent(getApplicationContext(), AppManagerActivity.class));
        mTabHost.addTab(tab5);

        mTabHost.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!mIsLandscape && !mIsPortraitInit) {
                    initTabAnimationParameter(mIsLandscape);
                    initTabMover(mIsLandscape);
                    onTabMoved(getTabHost().getCurrentTab());
                } else if (mIsLandscape && !mIsLandscapeInit) {
                    initTabAnimationParameter(mIsLandscape);
                    initTabMover(mIsLandscape);
                    onTabMoved(getTabHost().getCurrentTab());
                } else if (mIsRotated) {
                    if (!mIsPortraitInit || !mIsLandscapeInit) {
                        initTabAnimationParameter(mIsLandscape);
                    }
                    initTabMover(mIsLandscape);
                    onTabMoved(getTabHost().getCurrentTab());
                    mIsRotated = false;
                } else if (mIsRestore) {
                    mIsRestore = false;
                    initTabAnimationParameter(mIsLandscape);
                    initTabMover(mIsLandscape);
                    mTabHost.setCurrentTab(mLastTab);
                }
                return true;
            }
        });
        mTabHost.setOnTabChangedListener(this);
    }

    @Override
    public void onTabChanged(String tabId) {

        // 行为统计代码
        if (TAB_APP.equals(tabId)) {
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_1,
                    Constants.CLICK_MANAGER_TAB);
        } else if (TAB_CATEGORY.equals(tabId)) {
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_1,
                    Constants.CLICK_CATEGORY_TAB);
        } else if(TAB_RECOMMEND.equals(tabId)) {
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_1,
                    Constants.CLICK_RECOMMEND_TAB);
            
            View v = mTabHost.getTabWidget().getChildAt(2);
            ImageView icon = (ImageView) v.findViewById(R.id.tab_widget_icon);
            icon.setImageResource(ThemeManager.getResource(mSession,
                    ThemeManager.KEY_HOME_TAB_RECOMMEND));
            
        } else if (TAB_RANK.equals(tabId)) {
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_1, 
                    Constants.CLICK_RANK_TAB);
        } else if (TAB_HOME.equals(tabId)) {
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_1, 
                    Constants.CLICK_HOME_TAB);
        }
        onTabMoved(getTabHost().getCurrentTab());
    }
    
    /*
     * 开始背景动画移动
     */
    private void onTabMoved(int currentTab) {

        if (mMover == null) {
            initTabMover(mIsLandscape);
        }

        int endPos = 0;
        if (mIsLandscape) {
            // 横屏
            endPos = sStartPosArrayL[currentTab];
        } else {
            // 竖屏
            endPos = sStartPosArrayP[currentTab];
        }
        final TranslateAnimation animation = new TranslateAnimation(mStartX, endPos, 0, 0);
        animation.setDuration(400);
        animation.setFillAfter(true);
        mMover.startAnimation(animation);
        mStartX = endPos;
    }
    
    private static int[] sStartPosArrayP = new int[5];
    private static int[] sStartPosArrayL = new int[5];
    private static int sWidthP = 0;
    private static int sWidthL = 0;
    private boolean mIsPortraitInit;
    private boolean mIsLandscapeInit;
    private boolean mIsLandscape;
    private int mLastTab;
    private boolean mIsRestore;
    private boolean mIsRotated;
    
    /*
     * 初始化Tab Widget动画参数，获取每个Widget的宽度
     */
    private void initTabAnimationParameter(boolean isLandscape) {
        int tabWidth = mTabHost.getCurrentTabView().getWidth();
        if (isLandscape) {
            // 横屏的Tab起始位置
            int startPos = 0;
            for (int i = 0; i < 5; i++) {
                sStartPosArrayL[i] = startPos + tabWidth * i;
            }
            sWidthL = tabWidth;
            mIsLandscapeInit = true;
        } else {
            // 竖屏的Tab起始位置
            int startPos = 0;
            for (int i = 0; i < 5; i++) {
                sStartPosArrayP[i] = startPos + tabWidth * i;
            }
            sWidthP = tabWidth;
            mIsPortraitInit = true;
        }
    }
    
    /*
     * 初始化Tab的宽度
     */
    private void initTabMover(boolean isLandscape) {

        mMover = (ImageView) findViewById(R.id.iv_mover);
        mMover.setImageResource(ThemeManager.getResource(mSession,
                ThemeManager.KEY_HOME_TAB_INDICATOR));
        int tabHeight = mTabHost.getCurrentTabView().getHeight();
        if (isLandscape) {
            mMover.setLayoutParams(new FrameLayout.LayoutParams(sWidthL, tabHeight));
        } else {
            mMover.setLayoutParams(new FrameLayout.LayoutParams(sWidthP, tabHeight));
        }
    }

    /*
     * 创建TabWidgetView
     */
    private View createTabView(Context context, String text, int imageResource, View v) {

        View view = null;
        if (v == null) {
            view = LayoutInflater.from(context).inflate(R.layout.activity_home_tab_view, null);
        } else {
            view = v;
        }

        ImageView bg;
        if (imageResource == -1) {
            bg = (ImageView) view.findViewById(R.id.tab_widget_icon);
            if (mSession.getUpgradeNumber() > 0) {
                drawUpdateCount(this, getResources(), bg);
            } else {
                bg.setImageResource(ThemeManager.getResource(mSession,
                        ThemeManager.KEY_HOME_TAB_APP_MANAGER));
            }
        } else {
            bg = (ImageView) view.findViewById(R.id.tab_widget_icon);
            bg.setImageResource(ThemeManager.getResource(mSession, imageResource));
        }
        TextView textview = (TextView) view.findViewById(R.id.tab_widget_content);
        textview.setText(text);
        textview.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_HOME_TAB_TEXT));
        return view;
    }

    /*
     * 更新应用可更新数
     */
    private void drawUpdateCount(Activity context, Resources res, ImageView view) {
        
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inPurgeable = true;
        o.inInputShareable = true;
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        Bitmap cornerRes = BitmapFactory.decodeResource(res, R.drawable.main_tab_update, o);

        int theme = mSession.getTheme();
        Bitmap appBitmapNormal = null;
        Bitmap appBitmapPressed = null;

        if (theme == ThemeManager.THEME_TYPE_DARK) {
            appBitmapPressed = BitmapFactory.decodeResource(res, R.drawable.main_tab_app_selected,
                    o);
            appBitmapNormal = BitmapFactory.decodeResource(res, R.drawable.main_tab_app_normal, o);
        } else {
            appBitmapPressed = BitmapFactory.decodeResource(res,
                    R.drawable.main_tab_app_selected_light, o);
            appBitmapNormal = BitmapFactory.decodeResource(res,
                    R.drawable.main_tab_app_normal_light, o);
        }

        StateListDrawable stateDrawable = new StateListDrawable();
        int stateSelected = android.R.attr.state_selected;
        Bitmap cornerBitmap = drawText(theme, dm, res, cornerRes, mSession.getUpgradeNumber());
        Bitmap newBitmapNormal = drawBitmap(dm, appBitmapNormal, cornerBitmap);
        Bitmap newBitmapPressed = drawBitmap(dm, appBitmapPressed, cornerBitmap);

        stateDrawable.addState(new int[] { -stateSelected }, new BitmapDrawable(res,
                newBitmapNormal));
        stateDrawable.addState(new int[] { stateSelected }, new BitmapDrawable(res,
                newBitmapPressed));

        view.setImageDrawable(stateDrawable);

    }

    /*
     * 绘出背景图
     */
    private Bitmap drawBitmap(DisplayMetrics dm, Bitmap background, Bitmap corner) {
        Canvas canvas = new Canvas();
        final int height = background.getScaledHeight(dm);
        final int width = background.getScaledWidth(dm);
        Bitmap smallBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        canvas.setBitmap(smallBitmap);
        Paint textPainter = new Paint(Paint.ANTI_ALIAS_FLAG);
        canvas.drawBitmap(background, 0, 0, textPainter);
        textPainter.setXfermode(new PorterDuffXfermode(Mode.SRC_OVER));
        canvas.drawBitmap(corner, width - corner.getScaledWidth(dm), 0, textPainter);
        canvas.save();
        return smallBitmap;
    }

    /*
     * 绘出更新数字
     */
    private Bitmap drawText(int theme, DisplayMetrics dm, Resources res, Bitmap bm, int num) {
        final int height = bm.getScaledHeight(dm);
        final int width = bm.getScaledWidth(dm);
        Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawBitmap(bm, new Matrix(), new Paint());
        Paint textPainter = new Paint(Paint.ANTI_ALIAS_FLAG);
        
        if (theme == ThemeManager.THEME_TYPE_DARK) {
            textPainter.setColor(res.getColor(R.color.orange));
        } else {
            textPainter.setColor(res.getColor(R.color.color_e));
        }
        
        textPainter.setTextSize(dm.scaledDensity * 12);
        textPainter.setTypeface(Typeface.DEFAULT_BOLD);
        float textWidth = textPainter.measureText(String.valueOf(num)) / 2;
        canvas.drawText(String.valueOf(num), width / 2 - textWidth, height / 2
                + (dm.scaledDensity * 6), textPainter);
        canvas.save();
        return newBitmap;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.common_menus, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        switch (item.getItemId()) {
        case R.id.menu_account:
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_12,
                    Constants.MENU_CLICK_ACCOUNT);
            intent.setClass(getApplicationContext(), PersonalAccountFragment.class);
            startActivity(intent);
            break;

        case R.id.menu_setting:
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_12,
                    Constants.MENU_CLICK_SETTINGS);
            intent.setClass(getApplicationContext(), PreferenceActivity.class);
            startActivity(intent);
            break;

        case R.id.menu_more:
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_12, 
                    Constants.MENU_CLICK_ABOUT);
            intent.setClass(getApplicationContext(), MoreInfoActivity.class);
            startActivity(intent);
            break;

        case R.id.menu_feedback:
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_12,
                    Constants.MENU_CLICK_FEEDBACK);
            // 2012/9/17 移除友盟SDK跳转到论坛进行反馈
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("http://bbs.gfan.com/mobile/android-5028340-1-1.html?extra=page%3D1"));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            break;

        case R.id.menu_bbs:
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_12,
                    Constants.MENU_CLICK_BBS);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("http://bbs.gfan.com/mobile/"));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            break;

        case R.id.menu_exit:
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_12, 
                    Constants.MENU_CLICK_EXIT);
            if (!isFinishing()) {
                showDialog(DIALOG_EXIT);
            }
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (!isFinishing()) {
                showDialog(DIALOG_EXIT);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected Dialog onCreateDialog(final int id) {
        switch (id) {
        case DIALOG_EXIT:
            return new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle(getString(R.string.exit_gmarket))
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            // 退出机锋市场
                            exit();
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            try {
                                HomeTabActivity.this.dismissDialog(id);
                            } catch (IllegalArgumentException e) {
                            }
                        }
                    }).create();

        case DIALOG_OPT_UPDATE:

            String optVersionName = mSession.getUpdateVersionName();
            String optUpdateDesc = mSession.getUpdateVersionDesc();
            if (!TextUtils.isEmpty(optUpdateDesc)) {
                optUpdateDesc = optUpdateDesc.replace("\r", "");
            }
            return new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle(R.string.find_new_version)
                    .setMessage(getString(R.string.update_prompt, optVersionName) + optUpdateDesc)
                    .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            sendBroadcast(new Intent(Constants.BROADCAST_DOWNLOAD_OPT));
                            removeDialog(id);
                        }
                    })
                    .setNegativeButton(R.string.btn_next_time,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    sendBroadcast(new Intent(Constants.BROADCAST_REMIND_LATTER));
                                    removeDialog(id);
                                }
                            }).create();

        case DIALOG_FORCE_UPDATE:

            String forceVersionName = mSession.getUpdateVersionName();
            String forceUpdateDesc = mSession.getUpdateVersionDesc().replace("\r", "");
            return new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle(R.string.find_new_version)
                    .setMessage(
                            getString(R.string.update_prompt_stronger, forceVersionName)
                                    + forceUpdateDesc)
                    .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            sendBroadcast(new Intent(Constants.BROADCAST_DOWNLOAD));
                            removeDialog(id);
                        }
                    }).setNegativeButton(R.string.btn_exit, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            sendBroadcast(new Intent(Constants.BROADCAST_FORCE_EXIT));
                            removeDialog(id);
                        }
                    }).setOnCancelListener(new OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            sendBroadcast(new Intent(Constants.BROADCAST_FORCE_EXIT));
                        }
                    }).create();

        default:
            break;
        }
        return super.onCreateDialog(id);
    }

    @Override
    public void update(Observable arg0, Object arg1) {

        if (arg1 instanceof Integer) {
            if (Constants.INFO_UPDATE == (Integer) arg1) {
                
                // 刷新可更新应用数
                int counter = mSession.getUpgradeNumber();
                
                if (counter > 0 && counter != mUpdateCounter) {
                    mUpdateCounter = counter;
                    View v = getTabHost().getTabWidget().getChildTabViewAt(4);
                    drawUpdateCount(this, getResources(),
                            (ImageView) (v.findViewById(R.id.tab_widget_icon)));
                } else if (counter == 0) {
                    View v = getTabHost().getTabWidget().getChildTabViewAt(4);
                    ((ImageView) v.findViewById(R.id.tab_widget_icon))
                            .setImageResource(ThemeManager.getResource(mSession,
                                    ThemeManager.KEY_HOME_TAB_APP_MANAGER));
                }
            }
        }
    }

    /*
     * 检查是否有新的Splash
     */
    private void checkNewSplash() {
        sendBroadcast(new Intent(Constants.BROADCAST_SPLASH_CHECK_UPGRADE));
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onSuccess(int method, Object obj) {
        
        if (isFinishing()) {
            return;
        }
        
        if (method == MarketAPI.ACTION_CHECK_NEW_VERSION) {
            
            handleUpdate((UpdateInfo) obj);

        } else if (method == MarketAPI.ACTION_GET_REQUIRED) {

            handleInstallApp(((ArrayList<HashMap<String, Object>>) obj));
            
        } else if (method == MarketAPI.ACTION_CHECK_UPGRADE) {
            
            checkUpdateAppsNotification();
        } else if (method == MarketAPI.ACTION_GET_FOLLOWED_RECOMMEND) {
            
            checkFollowedNews((HashMap<String, Object>) obj);
        }
    }
    
    /*
     * 查询关注的专题是否有更新
     */
    private void checkFollowedNews(HashMap<String, Object> result) {
        
        int unread = (Integer) result.get(Constants.KEY_TOTAL_UNREAD);

        if (unread > 0) {

            View v = mTabHost.getTabWidget().getChildAt(2);
            ImageView icon = (ImageView) v.findViewById(R.id.tab_widget_icon);

            AnimationDrawable d = (AnimationDrawable) getResources().getDrawable(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_HOME_TAB_BREATH));
            icon.setImageDrawable(d);
            d.start();
        }
    }

    /*
     * 判断装机必备中应用与当前所安装的应用
     */
    private void handleInstallApp(ArrayList<HashMap<String, Object>> obj) {
        int count = 0;
        HashSet<String> installApps = mSession.getInstalledApps();

        for (HashMap<String, Object> map : obj) {
            String packageName = (String) map.get(Constants.KEY_PRODUCT_PACKAGE_NAME);
            if (installApps.contains(packageName)) {
                if (++count >= 5) {
                    return;
                }
            }
        }
        showNotification(count);
    }
    
    /*
     * 显示装机必备提醒
     */
    private void showNotification(int count) {
        mNotificationView = (RelativeLayout) findViewById(R.id.notification_bar);
        mNotificationContent = (TextView) findViewById(R.id.notification_content);
        mNotificationView.setOnClickListener(this);
        mNotificationView.setVisibility(View.VISIBLE);
        mHandler.sendEmptyMessageDelayed(HIDE_NOTIFICATION, NOTIFICATION_DURATION);
        SpannableStringBuilder style = new SpannableStringBuilder(getString(
                R.string.notification_first_login, count));
        style.setSpan(new TextAppearanceSpan(getApplicationContext(),
                R.style.first_login_number), 5, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mNotificationContent.setText(style);
    }
    
    /**
     * 显示一个类似于Toast的提示框
     */
    private void showTip(String tip,boolean format,Object... args){
        mTipView = (RelativeLayout) findViewById(R.id.tip_bar);
        mTipContent = (TextView) findViewById(R.id.tip_content);
        mTipView.setOnClickListener(this);
        mTipView.setVisibility(View.VISIBLE);
        mTipContent.setText(format ? String.format(tip, args) : tip);
    }
    
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case HIDE_NOTIFICATION:
                mNotificationView.setVisibility(View.GONE);
                break;
            case HIDE_TIPVIEW:
                mTipView.setVisibility(View.GONE);
            default:
                break;
            }
        };
    };

    @Override
    public void onError(int method, int statusCode) {
        if (method == MarketAPI.ACTION_CHECK_NEW_VERSION) {
            Utils.D("check new version fail because of status : " + statusCode);
        }
    }

    /*
     * 检查机锋市场的更新
     */
    private void handleUpdate(UpdateInfo info) {

        // 2011/9/21 fix NullPointerException
        if (mSession == null || info == null) {
            return;
        }

        // update the info to local memory
        int updateLevel = info.getUpdageLevel();
        mSession.setUpdateInfo(info.getVersionName(), info.getVersionCode(), info.getDescription(),
                info.getApkUrl(), updateLevel);
        File file = new File(getFilesDir(), Constants.UPDATE_FILE_NAME + ".apk");
        if (file.exists()) {
            file.delete();
        }
        // 有可用升级
        if (Constants.FORCE_UPDATE == updateLevel) {
            showDialog(DIALOG_FORCE_UPDATE);
        } else if (Constants.SUGGEST_UPDATE == updateLevel) {
            showDialog(DIALOG_OPT_UPDATE);
        }
    }

    /**
     * 退出机锋市场<br>
     * 进行必要的资源回收工作
     */
    private void doExit() {
        
        final Context context = getApplicationContext();
        //记录退出时间
        mSession.setUserLastLoginTime(System.currentTimeMillis());
        
        if (mSession.isSecondLogin()) {
            AlarmManageUtils.notifyCallbackService(this,
                AlarmManageUtils.PushRules.NOLOGIN_SILENCE_USER_7_DAY);
        } else {
            AlarmManageUtils.notifyCallbackService(this,
                AlarmManageUtils.PushRules.NOLOGIN_NEW_USER_3_DAY);
        }
        
        // 清除所有API缓存
        ResponseCacheManager.getInstance().clear();
        // 清除所有图片缓存
        CacheManager cache = CacheManager.getInstance(context);
        cache.clearExpiredFile(context);
        cache.clearFromMemory(context);
        // 清除坏通知
        Intent clearIntent = new Intent(context, DownloadService.class);
        clearIntent.putExtra(DownloadService.CLEAR_BAD_NOTIFICATION, 1);
        startService(clearIntent);
        // 2010/8/25 释放连接资源
        HttpClientFactory.get().close();
        if (mSession != null) {
            // 清除所有观察者
            mSession.deleteObservers();
            // 回收Session
            mSession.close();
            mSession = null;
        }
        AlarmManageUtils.scheduleUpdateAlarm(context);
        NotificationManager notificationManager = 
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(R.drawable.notification_icon);
        finish();
    }
    
    /**
     * 退出机锋市场
     */
    private void exit() {
        if (mSession != null && mSession.hasDownloadTask()) {
            moveTaskToBack(false);
        } else {
            doExit();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.notification_bar:
            Intent intent = new Intent(getApplicationContext(), InstallNecessaryActivity.class);
            startActivity(intent);
            break;
        case R.id.tip_bar:
//            Utils.jumpToPage(this, WebViewActivity.class, false,
//                    new String[] { Constants.EXTRA_APP_URL },
//                    new String[] { "http://bbs.gfan.com/m/android-4952121-1-1.html" });
            mHandler.sendEmptyMessage(HIDE_TIPVIEW);
        default:
            break;
        }
    }
    
    /** 创建对话框，询问是否创建桌面图标 */
    private void createDesktopIcon(){
        DialogUtil.createYesNoDialog(this, 0x12,
                getString(R.string.dialog_createDesktopIcon),
                new YesNoDialogListener() {

            @Override
            public void onYesDialog(int id) {
                Utils.createDesktopIcon(
                        HomeTabActivity.this, 
                        getResources().getString(R.string.app_name), 
                        R.drawable.app_icon, 
                        SplashActivity.class);
            }
            
            @Override
            public void onNoDialog(int id) {
                //do nothing
                return ;
            }
        }).show();
    }
}
